package com.dididoctor.doctor.Activity.Usercentre.Authentication;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dididoctor.doctor.Activity.ConstantValue;
import com.dididoctor.doctor.Adapter.PictureGridViewAdapter;
import com.dididoctor.doctor.Bean.IHandleUpload;
import com.dididoctor.doctor.Bean.ImageInfo;
import com.dididoctor.doctor.Bean.Token;
import com.dididoctor.doctor.Bean.workTitleLitapal;
import com.dididoctor.doctor.MV.EduActivity;
import com.dididoctor.doctor.MV.adapter.CommonAdapter;
import com.dididoctor.doctor.MV.adapter.ViewHolder;
import com.dididoctor.doctor.R;
import com.dididoctor.doctor.Ui.ItemListView;
import com.dididoctor.doctor.Ui.TagsGridView;
import com.dididoctor.doctor.Utils.ABFileUtil;
import com.dididoctor.doctor.Utils.MyToast;
import com.dididoctor.doctor.Utils.PhotoHelper;
import com.dididoctor.doctor.Utils.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * zhang
 * Created by boy on 2016/4/19.
 */
public class AuthenticationActivity extends EduActivity implements IHandleUpload, AuthenticationView {
    private TextView mTvTitle;
    private ImageView mBtnBack;
    private EditText mEtName, mEtDicardno;
    private TextView mEtHospital;
    private TagsGridView mGvImage;
    private ItemListView mIlvJobtitle;
    private SingleAdapter singleAdapter;
    private RelativeLayout mRelCameraAlbum;
    private ReplyImageAdapter adapter;
    //定义一个HashMap，用来存放单选按钮的值，Key是position
    HashMap<Integer, Object> hashMapSingle = new HashMap<Integer, Object>();

    //拍照  取消选择相机  选择图库的操作       认证
    private Button mBtnCancel, mBtnCamera, mBtnAlbum, mBtnConfirm;
    private PhotoHelper mPhotoHelper;
    private String capturePath = null;
    private int currOnclickImage = 0;
    private AuthenticationPresenter presenter;
    private String witId = "", witname = "";
    private final static int AUTHENTICATION_CITY = 310;
    public double Alllatitude, Alllongitude;
    public String AllAddressName;
    private String AllcityId = "", AllcityName = "";
    private TextView tv_pass;
    private List<ImageInfo> imageInfos = new ArrayList<>();
    private boolean isVersion = false;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_authentication);
    }

    @Override
    public void init() {
        /**初始化界面**/
        initView();

    }

    private void initView() {

        /**头部**/
        initTitleView();
        this.capturePath = ABFileUtil.getAppTmpPath() + "/TMP.jpg";
        mPhotoHelper = new PhotoHelper(this, capturePath);

        //姓名、身份证号、医院
        mEtName = (EditText) findViewById(R.id.et_name);
        mEtDicardno = (EditText) findViewById(R.id.et_dicardno);
        mEtHospital = (TextView) findViewById(R.id.et_hospital);
        mEtHospital.setOnClickListener(this);
        //资格认证图片
        mGvImage = (TagsGridView) findViewById(R.id.gv_image);
        //职称
        mIlvJobtitle = (ItemListView) findViewById(R.id.ilv_jobtitle);

        //选择拍照方式
        mRelCameraAlbum = (RelativeLayout) findViewById(R.id.rel_camera_album);

        //拍照  取消选择相机  选择图库的操作
        mBtnCancel = (Button) findViewById(R.id.btn_cancel);
        mBtnCancel.setOnClickListener(this);
        mBtnCamera = (Button) findViewById(R.id.btn_camera);
        mBtnCamera.setOnClickListener(this);
        mBtnAlbum = (Button) findViewById(R.id.btn_album);
        mBtnAlbum.setOnClickListener(this);


        //认证
        mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
        mBtnConfirm.setOnClickListener(this);


        //DAO层
        presenter = new AuthenticationPresenter(this, this);

        //认证结果
        tv_pass = (TextView) findViewById(R.id.tv_pass);
        if ("4".equals(Token.getIsPass())) {
//            witId = Token.getWtId();
            tv_pass.setVisibility(View.VISIBLE);
            mEtName.setText(Token.getName());
            //没有定位坐标的，让用户自己去重新定位获取位置
            mEtHospital.setText("");
            mEtDicardno.setText(Token.getIdNo());
            String[] strings1 = Token.getCertificateUrl().split(",");
            String[] stringid = Token.getCertificateID().split(",");
            for (int i = 0; i < strings1.length; i++) {
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setUrl(strings1[i]);
                imageInfo.setId(stringid[i]);
                imageInfo.setType(3);
                imageInfos.add(imageInfo);
            }
            adapter = new ReplyImageAdapter(this);
            if (strings1.length != 2){
                this.adapter.addImageSign();
            }
            adapter.addData(imageInfos);
            mGvImage.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            mBtnConfirm.setText("重新认证");
        } else {
            tv_pass.setVisibility(View.GONE);
            this.adapter = new ReplyImageAdapter(this);
            this.adapter.addImageSign();
            mGvImage.setAdapter(adapter);
        }
        initDataJobTitle();

    }

    private void initTitleView() {
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTitle.setText("资格认证");
        mBtnBack = (ImageView) findViewById(R.id.btn_back);
    }


    @Override
    public void onSubmitOver() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void addImage(ImageInfo imageInfo) {
        if (adapter.getData().size() < ConstantValue.MAX_PICTURE_NUMBER) {
            this.adapter.addData(imageInfo);
        } else {
            this.adapter.removeData(0);
            this.adapter.addData(imageInfo);
            isVersion = true;

        }
//        this.adapter.notifyDataSetChanged();
    }

    @Override
    public String getImageKeys() {
        return null;
    }

    @Override
    public void AuthenticationOk(String status) {
        Intent intent = new Intent(AuthenticationActivity.this, AuthenticationOkActivity.class);
        intent.putExtra("status", status);
        intent.putExtra("ispass", Token.getIsPass());
        startActivity(intent);
        Token.setIsPass("2");
        Token.setName(mEtName.getText().toString().trim());
        Token.setIdNo(mEtDicardno.getText().toString().trim());
        Token.setAddress(mEtHospital.getText().toString().trim());
        Token.setWtId(witId);
        StringBuffer sbid = new StringBuffer();
        StringBuffer sbUrl = new StringBuffer();
        for (int i = 0; i < adapter.getCount(); i++) {
            if (3 == adapter.getItem(i).getType()) {
                sbid.append(adapter.getItem(i).getId() + ",");
                sbUrl.append(adapter.getItem(i).getUrl() + ",");
            }
        }
        Token.setCertificateID(sbid.toString().substring(0, sbid.length() - 1));
        Token.setCertificateUrl(sbUrl.toString().substring(0, sbUrl.length() - 1));
        finish();
    }

    @Override
    public void AuthenticationDefeated(String status) {
        Intent intent = new Intent(AuthenticationActivity.this, AuthenticationOkActivity.class);
        intent.putExtra("status", status);
        startActivity(intent);
    }

    @Override
    public void DelectImage(String status, String imageId, int position) {
        if ("1".equals(status)) {
            if (adapter.getData().size() > 0) {
                if (adapter.getItem(0).getType() == 0){
                    this.adapter.removeData(position);
                }else{
                    this.adapter.removeData(position);
                    adapter.addImageSign();
                }
            }
        }
    }

    class ReplyImageAdapter extends PictureGridViewAdapter {

        public ReplyImageAdapter(Context context) {
            super(context);
        }

        @Override
        protected void handleExistImage() {

        }

        @Override
        protected void addImage() {
            mRelCameraAlbum.setVisibility(View.VISIBLE);
        }

        @Override
        protected void delectImage(ImageInfo item, int position) {
            presenter.delectImage(item.getId(), position);
        }
    }

    /**
     * 选择职称
     */
    public void initDataJobTitle() {
        //Listview处理
        final List<JobTitleBean> items = new ArrayList<JobTitleBean>();
        List<workTitleLitapal> getdisarases = new ArrayList<>();
        if (!Util.isEmpty(workTitleLitapal.getdisarases())) {
            getdisarases = workTitleLitapal.getdisarases();
        }
        for (workTitleLitapal map : getdisarases) {
            JobTitleBean inquiryItem = new JobTitleBean();
            inquiryItem.setId(map.getWtId());
            inquiryItem.setJobtitle(map.getName());
            items.add(inquiryItem);
        }
        singleAdapter = new SingleAdapter(AuthenticationActivity.this, items, witId);
        mIlvJobtitle.setAdapter(singleAdapter);
//        singleAdapter.notifyDataSetChanged();
        mIlvJobtitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                CheckBox mcb = (CheckBox) view.findViewById(R.id.item_cb);
                TextView textview = (TextView) view.findViewById(R.id.tv_diasease);
                for (int i = 0; i < items.size(); i++) {
                    hashMapSingle.put(i, false);
                }
                if (mcb.isChecked()) {
                    hashMapSingle.put(index, false);
                } else {
                    hashMapSingle.put(index, true);
                    witId = items.get(index).getId() + "";
                    witname = items.get(index).getJobtitle();
                }
                singleAdapter.notifyDataSetChanged();

            }
        });
    }


    class SingleAdapter extends CommonAdapter<JobTitleBean> {
        private CheckBox mCb;
        private TextView mTvDiasease;
        private List<JobTitleBean> datas;
        private String witId;

        public SingleAdapter(Context context, List<JobTitleBean> datas, String witId) {
            super(context, datas, R.layout.item_item_inquirycheck);
            this.datas = datas;
            this.witId = witId;
        }

        @Override
        public void convert(final int position, ViewHolder helper, final JobTitleBean item) {
            mCb = helper.getView(R.id.item_cb);
            mTvDiasease = helper.getView(R.id.tv_diasease);
            mTvDiasease.setText(item.getJobtitle());
            if (witId.equals(item.getId())) {
                mCb.setChecked(true);
            }
            if (hashMapSingle != null) {
                mCb.setChecked((Boolean) hashMapSingle.get(position));
            } else {
                mCb.setChecked(false);
            }

        }
    }


    public void setEable(EditText v, boolean b) {
        v.setEnabled(b);
    }

    @Override
    public void onClickEvent(View view) {

        switch (view.getId()) {
            case R.id.btn_cancel://取消
                this.mRelCameraAlbum.setVisibility(View.GONE);
                break;
            case R.id.btn_camera://选择相机
                mPhotoHelper.takePhoto();
                this.mRelCameraAlbum.setVisibility(View.GONE);
                break;
            case R.id.btn_album://本地选择
                mPhotoHelper.takePictureFromAlbum();
                this.mRelCameraAlbum.setVisibility(View.GONE);
                break;

            case R.id.et_hospital:
                Intent intent = new Intent(AuthenticationActivity.this, BaiDuMapActivity.class);
                startActivityForResult(intent, AUTHENTICATION_CITY);
                break;
            case R.id.btn_confirm:
                //真实姓名
                Token.setName(mEtName.getText().toString().trim());
                //身份证号
                Token.setIdNo(mEtDicardno.getText().toString().trim());
                //就职医院
                Token.setAddress(mEtHospital.getText().toString().trim());
                //就职医院
                List<ImageInfo> data = adapter.getData();
                StringBuffer certificateStrID = new StringBuffer();
                StringBuffer certificateStrUrl = new StringBuffer();
                for (ImageInfo map : data) {
                    certificateStrID.append(Util.toString(Util.toInteger(map.getId() + ",")));
                    certificateStrUrl.append(Util.toString(map.getUrl() + ","));
                }
                certificateStrID.substring(0, certificateStrID.length() - 1);
                certificateStrUrl.substring(0, certificateStrUrl.length() - 1);

                Token.setCertificateID(certificateStrID.toString());
                Token.setCertificateUrl(certificateStrUrl.toString());

                Token.setWtId(witId);
                if (ischeck()) {
                    if (mEtDicardno.getText().toString().trim().length() == 15 || mEtDicardno.getText().toString().trim().length() == 18) {
                        SubmitDialog submitDialog = new SubmitDialog(this, new SubmitDialog.Submitlistener() {
                            @Override
                            public void submitok() {
                                presenter.lunch(mEtName.getText().toString().trim(), mEtDicardno.getText().toString().trim(), mEtHospital.getText().toString().trim(), witId, Alllongitude, Alllatitude, AllcityId);
                            }
                        });
                        submitDialog.show();
                    } else {
                        showToastMessage("请输入正确的身份证号");
                    }
                }
                break;

        }

    }


    public boolean ischeck() {
        String name = mEtName.getText().toString().trim();
        String dicardNo = mEtDicardno.getText().toString().trim();
        String Hospital = mEtHospital.getText().toString().trim();

        if ("".equals(name) || name == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "请输入姓名", 0);
            return false;
        }

        if ("".equals(dicardNo) || dicardNo == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "请输入身份证号", 0);
            return false;
        }


        if ("".equals(Hospital) || Hospital == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "请选择就职医院地址", 0);
            return false;
        }


        if (adapter.getData() == null || adapter.getData().size() <= 1) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "请上传您的医生执业资格证", 0);
            return false;
        }

        if ("".equals(witId) || witId == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "请选择您的职称", 0);
            return false;
        }

        if ("".equals(Alllongitude + "") || Alllongitude + "" == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "没有获取到您就职医院经度，请打开定位，重新选择就职医院", 0);
            mEtHospital.setText("");
            return false;
        }

        if ("".equals(Alllatitude + "") || Alllatitude + "" == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "没有获取到您就职医院纬度，请打开定位，重新选择就职医院", 0);
            mEtHospital.setText("");
            return false;
        }

        if ("".equals(AllcityId) || AllcityId == null) {
            MyToast.DefaultmakeText(AuthenticationActivity.this, "没有获取到您就职医院城市，请打开定位，重新选择就职医院", 0);
            mEtHospital.setText("");
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPhotoHelper.TO_CAMEIA && resultCode == RESULT_OK) {//来自系统相机的返回
            mPhotoHelper.startPhotoZoom(Uri.fromFile(new File(capturePath)));
        } else if (requestCode == mPhotoHelper.TO_PHOTO && resultCode == RESULT_OK && data != null) {//来自系统相册的返回
            Uri uri = data.getData();
            mPhotoHelper.startPhotoZoom(uri);
        } else if (requestCode == ConstantValue.TO_OPENIMAGE && resultCode == ConstantValue.RESULT_DELETE) {//已经删除了照片
            this.adapter.removeData(this.currOnclickImage);
        } else if (requestCode == mPhotoHelper.TO_ZOOM_PHOTO && data != null) {//裁剪完成后
            this.presenter.updateImageFromUri(capturePath);
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case AUTHENTICATION_CITY:
                    AllAddressName = data.getStringExtra("addressStr");
                    Alllatitude = data.getDoubleExtra("latitude", 0);
                    Alllongitude = data.getDoubleExtra("longitude", 0);
                    AllcityName = data.getStringExtra("cityName");
                    AllcityId = data.getStringExtra("cityId");

                    mEtHospital.setText(AllAddressName);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mRelCameraAlbum.getVisibility() == View.VISIBLE) {
                mRelCameraAlbum.setVisibility(View.GONE);
            } else {
                finish();
            }
        }
        return true;
    }
}
